import axios from 'axios';
import * as path from 'path';
import * as fs from 'fs';
import {resolve} from "url";

let { convert } = require('html-to-text');

export function webRequest(url: string): Promise<string> {
    let header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36"
    };
    return new Promise((resovle, reject) => {
        axios.get(url, {
            headers: header
        })
            .then(res => {
                if (typeof res.data === 'string') {
                    resovle(res.data);
                } else {
                    resovle(JSON.stringify(res.data, undefined, 2));
                }
            });
    });
}

export function getBookChapters(url: string, htmlContent: string, start: string, end: string, regexStr: string): IChapter[] {
    htmlContent = htmlContent ?? "";
    let startIndex = 0;
    let endIndex = htmlContent.length;
    if (start) {
        startIndex = htmlContent.indexOf(start);
    }
    if (end) {
        endIndex = htmlContent.indexOf(end);
    }

    let matchContent = htmlContent.substring(startIndex, endIndex);

    let regex = new RegExp(regexStr, 'g');
    let regexResult;
    let list: IChapter[] = [];
    let maxcount = 2000;
    while (regexResult = regex.exec(matchContent)) {
        if (maxcount-- <= 0) {
            break;
        }
        list.push({
            link: regexResult.groups!["link"],
            title: regexResult.groups!["title"]
        });
    }

    let hostUrl = getHostFromUrl(url);
    list.forEach(item => {
        if (item.link.toLocaleLowerCase().startsWith("http")) {
            return;
        }
        item.link = resolve(url,item.link)
    });

    return list;
}

export function getBookContent(htmlContent: string, regexStr?: string): string {
    if (!regexStr) {
        return htmlContent;
    }

    let regex = new RegExp(regexStr, 'g');
    let regexResult = regex.exec(htmlContent);
    if (!regexResult) {
        return htmlContent;
    }
    let content = regexResult.groups!["content"];
    if (!content) {
        return "Unmatch " + new Date();
    } else {
        // remove html tag
        content = convert(content);
        return content;
    }

    return content;
}

export function mkdirs(folderPath: string) {
    var folders = [];
    var tmpPath = path.normalize(folderPath);
    var exists = fs.existsSync(tmpPath);
    while (!exists) {
        folders.push(tmpPath);
        tmpPath = path.join(tmpPath, '..');
        exists = fs.existsSync(tmpPath);
    }

    for (var i = folders.length - 1; i >= 0; i--) {
        //console.log(folders[i])
        fs.mkdirSync(folders[i]);
    }
}

export function getHostFromUrl(url: string) {
    let result = /^http[s]?\:\/\/[^\/]*/i.exec(url);
    if (!result) {
        return url;
    }

    return result[0];
}

export interface IChapter {
    sortId?: number;
    link: string;
    title: string;
}
